<template>
  <div class="container">
    <h2>学员新增与流失统计</h2>
    <el-divider />

    <!-- 表格展示 -->
    <el-table :data="pagedData" stripe>
      <el-table-column prop="studentId" label="学员ID" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="date" label="日期" />
      <el-table-column prop="month" label="月份" />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="allData.length"
      @current-change="handlePageChange"
    />

    <!-- 图表展示 -->
    <div class="chart-box" ref="chartDom" />
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const allData = ref([])
const pagedData = ref([])
const pageSize = 8
const currentPage = ref(1)

const handlePageChange = (page) => {
  currentPage.value = page
  const start = (page - 1) * pageSize
  const end = start + pageSize
  pagedData.value = allData.value.slice(start, end)
}

const chartDom = ref()
let chartInstance = null

onMounted(async () => {
  const [studentRes, statRes] = await Promise.all([
    axios.get('http://localhost:8080/api/students'),
    axios.get('http://localhost:8080/api/statistics')
  ])

  const students = Array.isArray(studentRes.data) ? studentRes.data : studentRes.data.data
  const stats = Array.isArray(statRes.data) ? statRes.data : statRes.data.data

  const chartNewMap = Array(12).fill(0)
  const chartLostMap = Array(12).fill(0)

  const tableRows = []

  // 新增数据
  students.forEach(s => {
    if (s.enrollmentDate) {
      const date = new Date(s.enrollmentDate)
      const month = date.getMonth()
      chartNewMap[month]++
      tableRows.push({
        studentId: s.studentId || '--',
        name: s.name || '--',
        type: '新增',
        date: s.enrollmentDate.slice(0, 10),
        month: `${month + 1}月`
      })
    }
  })

  // 流失数据
  stats.forEach(stat => {
    if (stat.expireDate && stat.status !== 'active') {
      const date = new Date(stat.expireDate)
      const month = date.getMonth()
      chartLostMap[month]++
      tableRows.push({
        studentId: stat.studentId || '--',
        name: '--',
        type: '流失',
        date: stat.expireDate.slice(0, 10),
        month: `${month + 1}月`
      })
    }
  })

  // 排序：按月份从早到晚
  tableRows.sort((a, b) => new Date(b.date) - new Date(a.date)) // 从新到旧


  allData.value = tableRows
  handlePageChange(1)

  await nextTick()
  drawChart(chartNewMap, chartLostMap)
})

const drawChart = (newData, lostData) => {
  if (!chartInstance && chartDom.value) {
    chartInstance = echarts.init(chartDom.value)
  }

  const option = {
    title: { text: '每月新增与流失人数统计', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['新增', '流失'], top: 30 },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
    },
    yAxis: { type: 'value', name: '人数' },
    series: [
      {
        name: '新增',
        type: 'bar',
        stack: '总量',
        data: newData,
        itemStyle: { color: '#ace0f9' }
      },
      {
        name: '流失',
        type: 'bar',
        stack: '总量',
        data: lostData,
        itemStyle: { color: '#fff1eb' }
      }
    ]
  }

  chartInstance.setOption(option)
  window.addEventListener('resize', () => chartInstance?.resize())
}
</script>
<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.pagination {
  margin: 20px 0;
  text-align: center;
}

.chart-box {
  height: 400px;
  margin-top: 40px;
}
</style>
